package net.zjitc.yaobei_backed.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import net.zjitc.yaobei_backed.entity.*;
import net.zjitc.yaobei_backed.repository.*;
import net.zjitc.yaobei_backed.service.WordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 单词服务实现
 */
@Service
public class WordServiceImpl implements WordService {

    @Autowired
    private StudyRecordRepository studyRecordRepository;

    @Autowired
    private WordRepository wordRepository;

    @Autowired
    private UserProgressRepository userProgressRepository;

    @Autowired
    private WordbookWordRepository wordbookWordRepository;

    @Override
    public List<Word> getTodayReviewWords(Integer userId, Integer limit) {
        // 1. 查询需要复习的学习记录（next_review_at <= NOW()，包括今天和已过期的）
        QueryWrapper<StudyRecord> recordWrapper = new QueryWrapper<>();
        recordWrapper.eq("user_id", userId);
        recordWrapper.apply("next_review_at <= NOW()"); // 包含今天及之前需要复习的
        recordWrapper.orderByAsc("next_review_at"); // 按复习时间排序，优先复习即将到期的
        recordWrapper.last("LIMIT " + limit);
        
        List<StudyRecord> records = studyRecordRepository.selectList(recordWrapper);
        
        // 2. 提取word_id列表
        List<Integer> wordIds = records.stream()
                .map(StudyRecord::getWordId)
                .collect(Collectors.toList());
        
        if (wordIds.isEmpty()) {
            return List.of();
        }
        
        // 3. 根据word_id查询单词信息
        QueryWrapper<Word> wordWrapper = new QueryWrapper<>();
        wordWrapper.in("id", wordIds);
        return wordRepository.selectList(wordWrapper);
    }

    @Override
    public List<Word> getNewWordsToLearn(Integer userId, Integer limit) {
        // 1. 获取用户当前学习的词书ID
        QueryWrapper<UserProgress> progressWrapper = new QueryWrapper<>();
        progressWrapper.eq("user_id", userId);
        UserProgress progress = userProgressRepository.selectOne(progressWrapper);
        
        if (progress == null || progress.getWordbookId() == null) {
            return List.of();
        }
        
        Integer wordbookId = progress.getWordbookId();
        
        // 2. 先查询用户已经学习过的单词ID（study_record中的word_id）
        QueryWrapper<StudyRecord> learnedWrapper = new QueryWrapper<>();
        learnedWrapper.eq("user_id", userId);
        learnedWrapper.select("word_id"); // 只查询word_id字段
        List<StudyRecord> learnedRecords = studyRecordRepository.selectList(learnedWrapper);
        
        List<Integer> learnedWordIds = learnedRecords.stream()
                .map(StudyRecord::getWordId)
                .collect(Collectors.toList());
        
        // 3. 查询该词书中的单词ID，排除已学习的，并限制数量
        QueryWrapper<WordbookWord> wordbookWordWrapper = new QueryWrapper<>();
        wordbookWordWrapper.eq("wordbook_id", wordbookId);
        // 如果已学习的单词不为空，排除这些单词
        if (!learnedWordIds.isEmpty()) {
            wordbookWordWrapper.notIn("word_id", learnedWordIds);
        }
        // 加上LIMIT限制，避免查询过多数据
        wordbookWordWrapper.orderByAsc("id"); // 按ID排序，保证结果稳定
        wordbookWordWrapper.last("LIMIT " + limit);
        List<WordbookWord> wordbookWords = wordbookWordRepository.selectList(wordbookWordWrapper);
        
        if (wordbookWords.isEmpty()) {
            return List.of();
        }
        
        // 4. 提取未学习过的单词ID
        List<Integer> newWordIds = wordbookWords.stream()
                .map(WordbookWord::getWordId)
                .collect(Collectors.toList());
        
        // 5. 查询未学习过的单词信息
        QueryWrapper<Word> wordWrapper = new QueryWrapper<>();
        wordWrapper.in("id", newWordIds);
        wordWrapper.orderByAsc("id"); // 按ID顺序返回
        return wordRepository.selectList(wordWrapper);
    }
}





